package com.eastfair.es;

import com.alibaba.fastjson.JSONObject;
import com.eastfair.core.base.R;
import com.eastfair.es.dao.AllLogDao;
import com.eastfair.es.dto.AllLogDto;
import com.eastfair.es.dto.EsPage;
import com.eastfair.es.entity.AllLog;
import com.eastfair.es.entity.PointLog;
import com.eastfair.es.hander.ElasticLowerClient;
import com.eastfair.es.service.AllLogService;
import com.eastfair.es.util.EsDeatilUtil;
import com.eastfair.es.util.EsWhereUtil;
import com.eastfair.es.vo.AllLogOfEs;
import com.eastfair.es.vo.AllLogSimpleVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;


/**
 * <p>
 * 前端控制器
 * 用户账户信息
 * </p>
 *
 * @author ligang
 * @date 2021-08-10
 */
@Slf4j
@Validated
@RestController
@RequestMapping("/alllog")
@Api(value = "alllog", tags = "总日志信息")
public class AllLogController {

    @Value("${spring.elasticsearch.rest.uris}")
    private String url;

    @Value("${spring.elasticsearch.rest.username}")
    private String username;

    @Value("${spring.elasticsearch.rest.password}")
    private String password;


    @Autowired
    AllLogDao allLogDao;

    @Autowired
    AllLogService allLogService;

    private ElasticLowerClient elasticLowerClient;
//    @Autowired
//    ElasticLowerClient elasticLowerClient;

    @RequestMapping(value = "/findById", method = RequestMethod.GET)
    @ResponseBody
    public R findById(String id) {
        AllLog allLog = (AllLog) allLogDao.get(id, AllLog.class);
        return R.success(allLog);
    }

    /*
    http://10.20.16.106:9200/all_log/_search?from=0&size=1000
    get
    {
    "query": {
        "bool": {
            "must": [
                {
                    "range": {
                        "dtTime": {
                            "gte": 1677342031000,
                            "lt": 1677448831000
                        }
                    }
                },
                {
                    "multi_match": {
                        "type": "cross_fields",
                        "query": "f7a86e720d0e49918fc5fdd227d4608c",
                        "fields": [
                            "traceId"
                        ],
                        "operator": "and"
                    }
                },
                {
                    "multi_match": {
                        "type": "cross_fields",
                        "query": "getByIdLead",
                        "fields": [
                            "detail"
                        ],
                        "operator": "and"
                    }
                }
            ]
        }
    }
}

     */

    @ResponseBody
    @PostMapping("/query")
    public R<AllLogOfEs> query(@RequestBody AllLogDto allLogDto) {
//        initelasticLowerClient();
//        String indexStr = "alllog";
////        String queryStr = "{\"query\":{\"bool\":{\"filter\":[[{\"multi_match\":{\"type\":\"cross_fields\",\"query\":\"findAllByChildIdNoButton\",\"fields\":[\"detail\"],\"operator\":\"or\"}},{\"multi_match\":{\"type\":\"cross_fields\",\"query\":\"6a95519452bf410690f5b94c0aee9565\",\"fields\":[\"traceId\"],\"operator\":\"or\"}},{\"range\":{\"dtTime\":{\"gte\":1676110434000,\"lt\":1676215003000}}}]],\"should\":[]}}}";
//        String queryStr = assmbileWhere(allLogDto);
//        String msg = null;
//        try {
//            msg = elasticLowerClient.get(indexStr, queryStr, allLogDto.getFrom(), allLogDto.getSize());
//            AllLogOfEs allLogOfEs = EsDeatilUtil.assmbleDetail(msg);
//            return R.success(allLogOfEs);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }

        return R.success(null);
    }


    @ResponseBody
    @PostMapping("/simpleQuery")
    public R<EsPage<List<AllLogSimpleVO>>> simpleQuery(@RequestBody EsPage<AllLogDto> esPage) {
        EsPage resultPage = new EsPage();
        BeanUtils.copyProperties(esPage, resultPage);
        initelasticLowerClient();
        String indexStr = "alllog";
//        String queryStr = "{\"query\":{\"bool\":{\"filter\":[[{\"multi_match\":{\"type\":\"cross_fields\",\"query\":\"findAllByChildIdNoButton\",\"fields\":[\"detail\"],\"operator\":\"or\"}},{\"multi_match\":{\"type\":\"cross_fields\",\"query\":\"6a95519452bf410690f5b94c0aee9565\",\"fields\":[\"traceId\"],\"operator\":\"or\"}},{\"range\":{\"dtTime\":{\"gte\":1676110434000,\"lt\":1676215003000}}}]],\"should\":[]}}}";
        String queryStr = assmbileWhere(esPage.getModel());
        log.info("simpleQuery queryStr is {}", queryStr);
        String msg = null;
        try {
            msg = elasticLowerClient.get(indexStr, queryStr, EsWhereUtil.queryFrom(esPage), EsWhereUtil.querySize(esPage));
            AllLogOfEs allLogOfEs = EsDeatilUtil.assmbleDetail(msg);
            List<AllLogSimpleVO> allLogSimpleVOList = EsDeatilUtil.assmbleDetailSimpleStrOfList(allLogOfEs.getAllLogVOList());
            allLogOfEs.setAllLogSimpleVOList(allLogSimpleVOList);
            allLogOfEs.setAllLogVOList(null);
            resultPage.setModel(allLogOfEs.getAllLogSimpleVOList());
            resultPage.setTotal(allLogOfEs.getNumber());
            return R.success(resultPage);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return R.success(null);
    }


    public String assmbileWhere(AllLogDto allLogDto) {
        /*{
            "query": {
                "bool": {
                    "must": [
                        {
                            "range": {
                                "dtTime": {
                                    "gte": 1677342031000,
                                    "lt": 1677448831000
                                }
                            }
                        },
                        {
                            "multi_match": {
                                "type": "cross_fields",
                                "query": "f7a86e720d0e49918fc5fdd227d4608c",
                                "fields": [
                                    "traceId"
                                ],
                                "operator": "and"
                            }
                        },
                        {
                            "multi_match": {
                                "type": "cross_fields",
                                "query": "getByIdLead",
                                "fields": [
                                    "detail"
                                ],
                                "operator": "and"
                            }
                        }
                    ]
                }
            }
        }*/

        StringBuffer stringBuffer = new StringBuffer();
        //开始
        //{"query":{"bool":{"must":[]}}}
        stringBuffer.append("{\"query\":{\"bool\":{\"must\":[");
        JSONObject jsonObject = JSONObject.parseObject(JSONObject.toJSONString(allLogDto));


        if (allLogDto.getDateTimeStart() != null && allLogDto.getDateTimeEnd() != null) {
//            {"range":{"dtTime":{"gte":1677342031000,"lt":1677448831000}}}
            stringBuffer.append(EsWhereUtil.rangeWhere("dtTime", allLogDto.getDateTimeStart(), allLogDto.getDateTimeEnd()));
        } else {
            //默认查15分钟数据
            Date start = new Date(System.currentTimeMillis() - (1000 * 60 * 15));
            stringBuffer.append(EsWhereUtil.rangeWhere("dtTime", start, new Date()));
        }

        for (String key : jsonObject.keySet()) {
            if (!("dateTime".equals(key) || "dateTimeStart".equals(key) || "dateTimeEnd".equals(key)
                    || "from".equals(key) || "size".equals(key))) {
                Object object = jsonObject.get(key);
                if (object != null) {
                    stringBuffer.append(",");
                    stringBuffer.append(EsWhereUtil.matchWhere(key, object));
                }
            }
        }

        //结束
        stringBuffer.append("]}}}");
        return stringBuffer.toString();
    }


    public void initelasticLowerClient() {
        if (elasticLowerClient == null) {
            elasticLowerClient = new ElasticLowerClient(url, username, password, false, false);
        }
    }

}
